# coding: utf-8
import json

from flask import (
    render_template, redirect, url_for, flash, request, jsonify
)

from app import db
from app.products.brand_forms import SpecSearchForm

from app.products.spec_froms import SpecForm
from . import product_bp
from .models import SpecTemplate, make_sure_json_list, ProductTemplate


@product_bp.route('/specs', methods=['GET', 'POST'])
def spec_list():
    """
    产品规格列表
    :return:
    """
    search_form = SpecSearchForm(formdata=request.form or request.args)

    search_args = {
        key: value for key, value in search_form.data.items() if value
    }

    spec_query = SpecTemplate.generate_list_query_condition(search_args)
    spec_query = spec_query.filter_by(deleted_at=0)

    pagination = spec_query.paginate(error_out=False)
    specs = pagination.items

    return render_template(
        'spec/spec_list.html',
        search_form=search_form,
        specs=specs,
        pagination=pagination,
        url_kwargs=search_args
    )


@product_bp.route('/add_spec', methods=['GET', 'POST'])
def add_spec():
    """
    新增产品规格模板
    :return:
    """
    form = SpecForm()

    if form.validate_on_submit():
        if not make_sure_json_list(form.options.data):
            flash('options字段值错误，更新失败')
            return redirect(url_for('product_bp.add_spec'))
        spec = SpecTemplate()
        form.populate_obj(spec)
        spec.options = json.loads(form.options.data)
        db.session.add(spec)
        db.session.flush()
        flash('新增产品规格模板成功')
        return redirect(url_for('product_bp.spec_list'))
    return render_template(
        "/spec/spec_add.html",
        form=form,
    )


@product_bp.route('/specs/<int:spec_id>', methods=['GET', 'POST'])
def edit_spec(spec_id):
    """
    编辑产品规格
    :param spec_id:
    :return:
    """

    spec = SpecTemplate.query.get_or_404(spec_id)
    if request.method == 'POST':
        form = SpecForm()
        form.product_type_id.data = spec.product_type_id
        if not make_sure_json_list(form.options.data):
            flash('options字段值错误，更新失败')
            return redirect(url_for('product_bp.edit_spec', spec_id=spec_id))

        if form.validate_on_submit():
            # 产品类型id不可修改
            form.populate_obj(spec)
            spec.options = json.loads(form.options.data)
            db.session.add(spec)
            db.session.flush()
            flash('更新产品规格成功')
            return redirect(
                url_for(
                    'product_bp.spec_list',
                    product_type_id=spec.product_type_id
                )
            )
        else:
            flash('编辑出错，请检查表单数据。')
            return redirect(url_for(
                'product_bp.edit_spec', spec_id=spec_id)
            )
    else:
        form = SpecForm(obj=spec, is_read_only=True)
        form.options.data = json.dumps(spec.options, ensure_ascii=False)
        # 编辑时产品类型不可修改
        form.product_type_id.choices = [
            (spec.product_type_id, spec.product_type_name)
        ]
        return render_template(
            "/spec/spec_info.html",
            form=form,
            spec_id=spec_id
        )


@product_bp.route('/ajax/spec/choices')
def ajax_spec_choices():
    """
    create by ld_wu 2018-01-04
    获取产品类下的产品规格
    :return:
    """
    product_type_id = request.args['product_type_id']
    return jsonify(
        SpecTemplate.spec_choices(product_type_id)
    )


@product_bp.route('/ajax/sync/specs', methods=['POST'])
def ajax_sync_specs():
    """
    同步产品规格
    :return:
    """
    try:
        product_id = request.get_json()['product_id']
        product_type_id = request.get_json()['product_type_id']
        product = ProductTemplate.get_by_id(product_id)
        template_mapping = SpecTemplate.spec_mapping(product_type_id)
        if product.spec_settings:
            for setting in product.spec_settings:
                template = template_mapping.get(setting['spec_templates_id'])
                if template:
                    template['values'] = setting['values']
        product.spec_settings = list(template_mapping.values())
        # status=0为同步成功
        return jsonify(dict(status=0))
    except Exception as e:
        # status=1为同步失败
        return jsonify(dict(status=1))